<?php
    /**
     * Created by PhpStorm.
     * User: wanghaitao
     * Date: 2017/10/16
     * Time: 下午2:55
     */
    namespace app\console\command;
    
    use think\console\Command;
    use think\console\Input;
    use think\console\Output;
    use think\console\input\Argument;
    use app\console\model\MessageBox;
    use app\console\model\Customer as CustomerModel;
    use think\Db;
    use think\Log;
    use think\Config;
    use think\cache\driver\Redis;
    use app\console\model\SendJpush;
    use app\console\model\MessageTargetUser as MessageTargetUserModel;
    /**
     * 计划任务 DATE
     * @author nick
     *
     */
    class Overdue extends Command{
        protected function configure(){
            
            $this->addArgument('page', Argument::REQUIRED); //必传参数
            $this->addArgument('pageLimit', Argument::REQUIRED);//可选参数
            $this->addArgument('msgID', Argument::REQUIRED); //必传参数
            $this->addArgument('addTime', Argument::REQUIRED);//可选参数
            
            $this->setName('Overdue')->setDescription('逾期用户发送push消息');
        }
        
        protected function execute(Input $input, Output $output){
            $output->writeln('Overdue脚本运行Start');
            $args = $input->getArguments();
            
            (int)$args['page'] ? $page=(int)$args['page']:json(['msg'=>'page is not a num','code'=>Constant::ERROR,'data'=>[]])->send();
            (int)$args['pageLimit'] ? $pageLimit=(int)$args['pageLimit']:json(['msg'=>'pageLimit is not a num','code'=>Constant::ERROR,'data'=>[]])->send();
            (int)$args['msgID'] ? $msgID=(int)$args['msgID']:json(['msg'=>'msgID is not a num','code'=>Constant::ERROR,'data'=>[]])->send();
            (int)$args['addTime'] ? $addTime=(int)$args['addTime']:json(['msg'=>'addTime is not a num','code'=>Constant::ERROR,'data'=>[]])->send();
    
            $logName='page：'.$page.'<>pageLimit:'.$pageLimit.'<>msgID:'.$msgID.'<>addTime:'.$addTime."=>";
            Log::write('executeStart:'.$logName);
    
            // 每批次插入开始时间
            $s_time = microtime(true);
            Log::write($logName.'开始时间=>'.$s_time);
    
            $data=Db::connect(Config::get("tianshendai_read"))->name('consume_history')->query(
                "
            SELECT
                consume_history.system_type,consume_history.customer_id
            FROM
                consume_installment_history
            LEFT JOIN consume_history ON consume_history.id=consume_installment_history.parent_id
            WHERE
                consume_installment_history.`repayment_time` < now()
            AND 
                consume_installment_history.status=0
            GROUP BY
                consume_installment_history.parent_id
            ORDER BY
                consume_history.id ASC LIMIT {$page},{$pageLimit}
            ");
            
            $pushModel=new SendJpush;
            $customerModel=new CustomerModel;
            if(!empty($data)){
                foreach ($data as $v){
    
                    Log::write($logName.'遍历处理=>'.json_encode($v));
                    
                    $data2=$customerModel->getPushIdByCustomerID($v['customer_id']);
                    $isActive=$this->customerIsActive($v['customer_id']);
                    if(!$data2['push_id'] || !$isActive){
                        continue;
                    }
                    
                    $pushData=['pushId'=>$data2['push_id'],'systemType'=>$v['system_type']];
//                    $pushData=['pushId'=>'1a0018970a9ea92c439','systemType'=>$v['system_type']];
                    $re=$pushModel->pushUnreadMessages($pushData);
                    $pushRe=json_decode($re,true);
                    $status=1;
                    if(isset($pushRe['sendno']) && $pushRe['sendno']=='0'){
                        $status=2;
                    }
    
                    Log::write($logName.'发送jpush数据=>'.json_encode($pushData).'<>jpush结果=>'.$re);
                    
                    
                    $addData=['m_b_id'=>$msgID,'customer_id'=>$v['customer_id'],'type'=>2,'jpush_send_status'=>$status,'add_time'=>time()];
                    $messageTargetUserModel=new MessageTargetUserModel;
                    $messageTargetUserModel->addMessageTargetUserData($addData,$addTime);
                    
                }
            }
            // 每批次插入结束时间
            $e_time = microtime(true);
    
            // 每批次插入耗费的时间
            $duration = $e_time - $s_time;
            $output->writeln('耗时:'.$duration);
            Log::write($logName.'耗时=>'.$duration);
            $output->writeln('Overdue脚本运行end');
        }
        
        /*
         * 返回用户是否处于活跃状态
         */
        private function customerIsActive($customerID) {
            if(!(int)$customerID)return false;
            $redis=new Redis(Config::get('redis'));
            $cacheKey = 'To'.$customerID.'ken';
            if(!$redis->get($cacheKey)){//用户不处于活跃状态
                return false;
            }
            return true;
        }
        
    }